package com.phoenix.shuaidatabase.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class PrintThreadRetry implements Runnable{

    static int n = 100;

    static int cur = 1;

    static int cap = 3;

    int k;

    static ArrayList<Object> locks = new ArrayList<>();

    static {
        locks.add(new Object());
        locks.add(new Object());
        locks.add(new Object());
    }

    PrintThreadRetry(int k) {
        this.k = k;
    }

    @Override
    public void run() {
        while(cur <= n) {
            int pre = (k - 1 + cap)%cap;
            synchronized (locks.get(pre)) {
                synchronized (locks.get(k)) {
                    System.out.println("线程" + k + "打印:" + cur);
                    cur++;
                    locks.get(k).notify();
                }
                try {
                    locks.get(pre).wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        synchronized (locks.get(k)) {
            locks.get(k).notify();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        PrintThreadRetry thread1 = new PrintThreadRetry(0);
        PrintThreadRetry thread2 = new PrintThreadRetry(1);
        PrintThreadRetry thread3 = new PrintThreadRetry(2);
        List<PrintThreadRetry> threads = Arrays.asList(thread1, thread2, thread3);
        for(PrintThreadRetry thread : threads) {
            new Thread(thread).start();
            Thread.sleep(10);
        }
    }
}
